package com.org.utils.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;
/***
 * 
 * @author liangjilong
 * @Description：数据库帮助类..
 */

@SuppressWarnings("all")
public class DBHelper {
	
	private static DBHelper instance = null;
	private static Connection conn = null;
	private static Statement stmt = null;
	private static PreparedStatement preparedStatement = null;
	private static CallableStatement callableStatement = null;
	private static ResultSet rs = null;
	
	private static String Driver = "com.mysql.jdbc.Driver";// ConfigUtils.getProperty("jdbc.driver");
	private static String Url = "jdbc:mysql://localhost:3306/weixin?characterEncoding=utf8";// ConfigUtils.getProperty("jdbc.url");
	private static String UserName = "root";// ConfigUtils.getProperty("jdbc.userName");
	private static String PassWord = "root";// ConfigUtils.getProperty("jdbc.passWord");

	/**建立单例模式
	 * Single
	 * @return
	 */
	public static DBHelper getInstance() {
		if (instance == null) {
			synchronized (DBHelper.class) {
				instance = new DBHelper();
			}
		}
		return instance;
	}

	/**
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(Driver);
			conn = DriverManager.getConnection(Url, UserName, PassWord);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * method3: 专门用于发送增删改语句的方法
	 * @param pstmt
	 * @return
	 */
    public static int execOther(PreparedStatement pstmt){
        try {
            //1、使用Statement对象发送SQL语句
            int affectedRows = pstmt.executeUpdate();
            //2、返回结果
            return affectedRows;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }


    /***
     * method4: 专门用于发送查询语句
     * @param pstmt
     * @return
     */
    public static ResultSet execQuery(PreparedStatement pstmt){
        try {
            //1、使用Statement对象发送SQL语句
            rs = pstmt.executeQuery();
            //2、返回结果
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
	

	/**
	 * 支持批量处理delete update insert
	 * 
	 * @param sqls
	 * @return
	 */
	public int supportsBatch(Object[] sqls) {
		try {
			conn = DBHelper.getInstance().getConnection();
			conn.setAutoCommit(false);
			DatabaseMetaData dma = conn.getMetaData();
			if (dma.supportsBatchUpdates()) {
				stmt = conn.createStatement();
				for (int i = 0; i < sqls.length; i++) {
					stmt.addBatch(sqls[i] + "");
				}
				int[] rows = stmt.executeBatch();
				conn.commit();
				return rows.length;
			} else {
				return sqls.length;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ReleaseUtils.releaseAll(null, stmt, conn);
		}
		return 0;
	}

	/**
	 * 执行查询
	 * 
	 * @param sql
	 * @param args
	 * @return javax.servlet.jsp.jstl.sql.Result;
	 */
	public static Result executeQuery(String sql, Object[] args) {
		// JSTL中提供的类,因此要导入JSTL的两个jar包
		Result result = null;
		Connection conn = null;
		PreparedStatement state = null;
		ResultSet rs = null;
		try {
			conn = DBHelper.getInstance().getConnection();
			state = conn.prepareStatement(sql);
			if (args != null && args.length > 0) {
				for (int i = 0; i < args.length; i++) {
					state.setObject(i + 1, args[i]);
				}
			}
			rs = state.executeQuery();
			result = ResultSupport.toResult(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ReleaseUtils.releaseAll(rs, state, conn);
		}
		return result;
	}

	/**
	 * 执行(增删改)
	 * 
	 * @param sql
	 * @param args
	 * @return boolean
	 */
	public static boolean executeUpdate(String sql, Object[] args) {
		boolean sign = false;
		Connection conn = null;
		PreparedStatement state = null;
		try {
			conn = getConnection();
			state = conn.prepareStatement(sql);
			if (args != null && args.length > 0) {
				for (int i = 0; i < args.length; i++) {
					state.setObject(i + 1, args[i]);
				}
			}
			int rows = state.executeUpdate();
			if (rows > 0)
				sign = true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			ReleaseUtils.releaseAll(null, state, conn);
		}
		return sign;
	}

	
	
	
	 /**
     * 用于查询，返回结果集
     *
     * @param sql
     *            sql语句
     * @return 结果集
     * @throws SQLException
     */
    public static List query(String sql) throws SQLException {
        ResultSet rs = null;
        try {
            getPreparedStatement(sql);
            rs = preparedStatement.executeQuery();
            return ResultToListMap(rs);
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 用于带参数的查询，返回结果集
     *
     * @param sql
     *            sql语句
     * @param paramters
     *            参数集合
     * @return 结果集
     * @throws SQLException
     */
    @SuppressWarnings("rawtypes")
    public static List query(String sql, Object... paramters) throws SQLException {
        ResultSet rs = null;
        try {
            getPreparedStatement(sql);
            for (int i = 0; i < paramters.length; i++) {
                preparedStatement.setObject(i + 1, paramters[i]);
            }
            rs = preparedStatement.executeQuery();
            return ResultToListMap(rs);
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 返回单个结果的值，如count\min\max等等
     *
     * @param sql
     *            sql语句
     * @return 结果集
     * @throws SQLException
     */
    public static Object getSingle(String sql) throws SQLException {
        Object result = null;
        ResultSet rs = null;
        try {
            getPreparedStatement(sql);
            rs = preparedStatement.executeQuery();
            if (rs.next()) {
                result = rs.getObject(1);
            }
            return result;
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 返回单个结果值，如count\min\max等
     *
     * @param sql
     *            sql语句
     * @param paramters
     *            参数列表
     * @return 结果
     * @throws SQLException
     */
    public static Object getSingle(String sql, Object... paramters) throws SQLException {
        Object result = null;
        ResultSet rs = null;
        try {
            getPreparedStatement(sql);
            for (int i = 0; i < paramters.length; i++) {
                preparedStatement.setObject(i + 1, paramters[i]);
            }
            rs = preparedStatement.executeQuery();
            if (rs.next()) {
                result = rs.getObject(1);
            }
            return result;
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 用于增删改
     *
     * @param sql
     *            sql语句
     * @return 影响行数
     * @throws SQLException
     */
    public static int update(String sql) throws SQLException {
        try {
            getPreparedStatement(sql);
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free();
        }
    }
 
    /**
     * 用于增删改（带参数）
     *
     * @param sql
     *            sql语句
     * @param paramters
     *            sql语句
     * @return 影响行数
     * @throws SQLException
     */
    public static int update(String sql, Object... paramters) throws SQLException {
        try {
            getPreparedStatement(sql);
            for (int i = 0; i < paramters.length; i++) {
                preparedStatement.setObject(i + 1, paramters[i]);
            }
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free();
        }
    }
 
    /**
     * 插入值后返回主键值
     *
     * @param sql
     *            插入sql语句
     * @return 返回结果
     * @throws Exception
     */
    public static Object insertWithReturnPrimeKey(String sql) throws SQLException {
        ResultSet rs = null;
        Object result = null;
        try {
            conn = DBHelper.getInstance().getConnection();
            preparedStatement = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            preparedStatement.execute();
            rs = preparedStatement.getGeneratedKeys();
            if (rs.next()) {
                result = rs.getObject(1);
            }
            return result;
        } catch (SQLException e) {
            throw new SQLException(e);
        }
    }
 
    /**
     * 插入值后返回主键值
     *
     * @param sql
     *            插入sql语句
     * @param paramters
     *            参数列表
     * @return 返回结果
     * @throws SQLException
     */
    public static Object insertWithReturnPrimeKey(String sql, Object... paramters) throws SQLException {
        ResultSet rs = null;
        Object result = null;
        try {
            conn =DBHelper.getInstance().getConnection();
            preparedStatement = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            for (int i = 0; i < paramters.length; i++) {
                preparedStatement.setObject(i + 1, paramters[i]);
            }
            preparedStatement.execute();
            rs = preparedStatement.getGeneratedKeys();
            if (rs.next()) {
                result = rs.getObject(1);
            }
            return result;
        } catch (SQLException e) {
            throw new SQLException(e);
        }
 
    }
 
    /**
     * 调用存储过程执行查询
     *
     * @param procedureSql
     *            存储过程
     * @return
     * @throws SQLException
     */
    @SuppressWarnings("rawtypes")
    public static List callableQuery(String procedureSql) throws SQLException {
        ResultSet rs = null;
        try {
            getCallableStatement(procedureSql);
            rs = callableStatement.executeQuery();
            return ResultToListMap(rs);
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 调用存储过程（带参数）,执行查询
     *
     * @param procedureSql
     *            存储过程
     * @param paramters
     *            参数表
     * @return
     * @throws SQLException
     */
    @SuppressWarnings("rawtypes")
    public static List callableQuery(String procedureSql, Object... paramters) throws SQLException {
        ResultSet rs = null;
        try {
            getCallableStatement(procedureSql);
            for (int i = 0; i < paramters.length; i++) {
                callableStatement.setObject(i + 1, paramters[i]);
            }
            rs = callableStatement.executeQuery();
            return ResultToListMap(rs);
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 调用存储过程，查询单个值
     * @param procedureSql
     * @return
     * @throws SQLException
     */
    public static Object callableGetSingle(String procedureSql) throws SQLException {
        Object result = null;
        ResultSet rs = null;
        try {
            getCallableStatement(procedureSql);
            rs = callableStatement.executeQuery();
            while (rs.next()) {
                result = rs.getObject(1);
            }
            return result;
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    /**
     * 调用存储过程(带参数)，查询单个值
     * @param procedureSql
     * @param parameters
     * @return
     * @throws SQLException
     */
    public static Object callableGetSingle(String procedureSql, Object... paramters) throws SQLException {
        Object result = null;
        ResultSet rs = null;
        try {
            getCallableStatement(procedureSql);
            for (int i = 0; i < paramters.length; i++) {
                callableStatement.setObject(i + 1, paramters[i]);
            }
            rs = callableStatement.executeQuery();
            while (rs.next()) {
                result = rs.getObject(1);
            }
            return result;
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free(rs);
        }
    }
 
    public static Object callableWithParamters(String procedureSql) throws SQLException {
        try {
            getCallableStatement(procedureSql);
            callableStatement.registerOutParameter(0, Types.OTHER);
            callableStatement.execute();
            return callableStatement.getObject(0);
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free();
        }
    }
 
    /**
     * 调用存储过程，执行增删改
     * @param procedureSql
     *            存储过程
     * @return 影响行数
     * @throws SQLException
     */
    public static int callableUpdate(String procedureSql) throws SQLException {
        try {
            getCallableStatement(procedureSql);
            return callableStatement.executeUpdate();
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free();
        }
    }
 
    /**
     * 调用存储过程（带参数），执行增删改
     * @param procedureSql
     *            存储过程
     * @param parameters
     * @return 影响行数
     * @throws SQLException
     */
    public static int callableUpdate(String procedureSql, Object... parameters) throws SQLException {
        try {
            getCallableStatement(procedureSql);
            for (int i = 0; i < parameters.length; i++) {
                callableStatement.setObject(i + 1, parameters[i]);
            }
            return callableStatement.executeUpdate();
        } catch (SQLException e) {
            throw new SQLException(e);
        } finally {
        	ReleaseUtils.free();
        }
    }
 
    /**
     * 批量更新数据
     * @param sqlList
     *            一组sql
     * @return
     */
    public static int[] batchUpdate(List<String> sqlList) {
        int[] result = new int[] {};
        Statement statenent = null;
        try {
            conn = DBHelper.getInstance().getConnection();
            conn.setAutoCommit(false);
            statenent = conn.createStatement();
            for (String sql : sqlList) {
                statenent.addBatch(sql);
            }
            result = statenent.executeBatch();
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new ExceptionInInitializerError(e1);
            }
            throw new ExceptionInInitializerError(e);
        } finally {
        	ReleaseUtils.free(statenent, null);
        }
        return result;
    }
 
    private static List ResultToListMap(ResultSet rs) throws SQLException {
        List list = new ArrayList();
        while (rs.next()) {
            ResultSetMetaData md = rs.getMetaData();
            Map map = new HashMap();
            for (int i = 1; i <= md.getColumnCount(); i++) {
                map.put(md.getColumnLabel(i), rs.getObject(i));
            }
            list.add(map);
        }
        return list;
    }
 
    /**
     * 获取PreparedStatement
     * @param sql
     * @throws SQLException
     */
    private static void getPreparedStatement(String sql) throws SQLException {
        conn = DBHelper.getInstance().getConnection();
        preparedStatement = conn.prepareStatement(sql);
    }
 
    /**
     * 获取CallableStatement
     * @param procedureSql
     * @throws SQLException
     */
    private static void getCallableStatement(String procedureSql) throws SQLException {
        conn = DBHelper.getInstance().getConnection();
        callableStatement = conn.prepareCall(procedureSql);
    }
  
}
